<?php
require_once(dirname(__FILE__).'/calendarSyncCommon.php');
ob_start();
Util::cleanRequest();

$authorized = false;// CirrusInsight::Authorized();
if ($authorized) {
	if (array_key_exists('state', $_REQUEST) && $_REQUEST["state"] == "person") {
		$detail = array(); $detail["email"] = $state->data->email;
		$person = CirrusInsight::getCIPerson($detail);
		CirrusInsight::ServiceResponse(true, $person, false);
		outputPostMessage($person);

	} else {
		outputPostMessage(CirrusInsight::ServiceResponse(true));

	}
} else {
    
	if (!array_key_exists('code', $_REQUEST)) {
		if (array_key_exists('continue', $_REQUEST)) {
			// Request authorization from salesforce user.
			$auth_code_url = SFDC_AUTH_CODE_URL;
			if (array_key_exists('state', $_REQUEST)) $auth_code_url .= '&state=' . $_REQUEST['state']; // Pass in the context of the email along with the log in request
			header('Location: ' . $auth_code_url);
		} else {
			// show splash
			include('sfdcLoginSplash.php');
		}
	} else {
		// Received authorization. Get token.
                
		$authorization_code = urldecode($_REQUEST['code']);
		$state = null; 
		if (array_key_exists('state', $_REQUEST)) 
			$state = json_decode(urldecode($_REQUEST['state']));
			
		$access_token_url = SFDC_ACCESS_TOKEN_URL . urlencode($authorization_code);
		
		// grab URL and parse it
		$json = Util::callout($access_token_url, 'POST');
                outputPostMessage(CirrusInsight::ServiceResponse(false, $json));
		if (isset($json->data->error) || (isset($state->debug) && $state->debug == 'auth')) {
			unset($_SESSION);
			outputPostMessage(CirrusInsight::ServiceResponse(false, $json));
			exit;
		}
                // Get the user's details
                $id_service = new stdClass();
		$id_service = Util::callout($json->data->id, 'GET', $headers=array('Authorization: OAuth '.$json->data->access_token));
                outputPostMessage(CirrusInsight::ServiceResponse(false, $id_service));
		if (isset($json->data->error) || (isset($state->debug) && $state->debug == 'id')) {
			unset($_SESSION);
			outputPostMessage(CirrusInsight::ServiceResponse(false, $id_service));
			exit;
		}
		
		$_SESSION["access_token"] = $json->data->access_token;
		$insightUser = new InsightUser($id_service->data->user_id);
		$newUser = (!$insightUser->user_id);
		
		$insightUser->username = $id_service->data->username;
		$insightUser->email = $id_service->data->email;
		$insightUser->display_name = $id_service->data->display_name;
		$insightUser->utcOffset = ($id_service->data->utcOffset / 1000 / 60 / 60);
		$insightUser->refresh_token = Util::encrypt($json->data->refresh_token);
		echo 'Print Insight User Object here';
                var_dump($insightUser);
		if ($newUser) {
			$insightUser->user_id = $id_service->data->user_id;
			$insightUser->locale = $id_service->data->locale;
			$insightUser->org_id = $id_service->data->organization_id;
			$insightUser->partner_api = str_replace('{version}', API_VERSION, $id_service->data->urls->partner);
			$insightUser->signup_date = date("Y-m-d");
			$insightUser->trial_exp_date = date("Y-m-d", time() + (TRIAL_PERIOD * 24 * 60 * 60));
			$insightUser->status = 'trial';

			// give salesforce employees free demo licenses
			if (stripos($insightUser->email, 'salesforce.com') !== FALSE) {
				$insightUser->status = 'active';
			}
			
			$insightUser->license_type = 0;

			$result = $insightUser->insert();
			
			if (!$result) {
				// This will immediately email ME - not log a case.
				Util::mailCI('Insight User creation failure', array($insightUser, $id_service, $json), false);
				unset($_SESSION);
				outputPostMessage(CirrusInsight::ServiceResponse(false));
				exit;
			}
		} else {
			$insightUser->update();
		}
		
		$insightUser->createSession($json->data->access_token);
	
		// Create a Lead in the Cirruspath org
		if ($newUser && INSIGHT_TEST == false) { // don't create a lead if working in the test environment
			try {
				$orgInfo = Salesforce::getOrgInfo();
				$userInfo = Salesforce::getUserInfo($insightUser->user_id);
				
				$lead = new SObject();
				$lead->type = 'Lead';
				$lead->fields = array(
					"FirstName" 						=> $userInfo->fields->FirstName,
					"LastName" 							=> $userInfo->fields->LastName,
					"Email" 								=> $userInfo->fields->Email,
					"Title" 								=> $userInfo->fields->Title,
					"Phone" 								=> $userInfo->fields->Phone,
					"MobilePhone" 					=> $userInfo->fields->MobilePhone,
					"LeadSource" 						=> 'Cirrus Insight Activation',
					"Status"								=> 'Open',
					"Salesforce_User_ID__c"	=> $insightUser->user_id,
					"Trial_Expiration_Date__c"	=> $insightUser->trial_exp_date,
					
					"Company" 							=> Util::coalesce($orgInfo->org->fields->Name, $insightUser->org_id),
					"Street" 								=> (isset($orgInfo->org) ? $orgInfo->org->fields->Street : ''),
					"City" 									=> (isset($orgInfo->org) ? $orgInfo->org->fields->City : ''),
					"State" 								=> (isset($orgInfo->org) ? $orgInfo->org->fields->State : ''),
					"PostalCode" 						=> (isset($orgInfo->org) ? $orgInfo->org->fields->PostalCode : ''),
					"Country" 							=> (isset($orgInfo->org) ? $orgInfo->org->fields->Country : ''),
					"Salesforce_Org_Type__c"=> (isset($orgInfo->org) ? $orgInfo->org->fields->OrganizationType : ''),
					"NumberOfEmployees" 		=> $orgInfo->numUsers,
					"Salesforce_Org_ID__c"	=> $insightUser->org_id,
					"Language_Locale__c" 		=> $insightUser->locale
				);
				
				if (array_key_exists("insight_referrer", $_COOKIE)) {
					$lead->fields["Referral_Code__c"] = $_COOKIE["insight_referrer"];
				}
				
				Salesforce::$cirruspath = true;
				$cp_conn = Salesforce::connect(); 
				$response = $cp_conn->create(array($lead));
			} catch (Exception $e) {
				Util::logCase('Error Creating Lead', array("EXCEPTION"=>$e, "LEAD_INFO"=>$lead));
				Salesforce::$cirruspath = false;
			}
		}

		$insightUser->setInsightToken();
		// Check the state and run the request if possible
		if ($state != null && $state->request == 'person') {
			$detail = array(); $detail["email"] = $state->data->email;
			if (!isset($_SESSION["describe"])) Salesforce::getDescribe();
			$person = CirrusInsight::getCIPerson($detail);
			outputPostMessage(CirrusInsight::ServiceResponse(true, $person, false));
		} else {
			outputPostMessage(CirrusInsight::ServiceResponse(true));
		}
	}
}

function outputPostMessage($message) {
	$out = '<html><head><script type="text/javascript">';
	$out .= 'window.opener.postMessage("' . addslashes($message) . '", "*");';
	$out .= 'window.close();';
	$out .= '</script>';
	$out .= '<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">';
	$out .= '</head></html>';
	echo $out;
}
?>